<template>
    <div class="p-2">
        <searchrevealing>
            <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="88px">
                <el-form-item label="入库类型" prop="putStockType">
                    <el-select v-model="queryParams.putStockType" placeholder="请选择入库类型" clearable style="width: 220px"
                        filterable @change="onChange">
                        <el-option v-for="dict in ReasonstorageList" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <!-- 招商入库 -->
                <el-form-item label="来源部门" prop="recruiterDeptId" v-if="queryParams.putStockType == 'E1'">
                    <el-select style="width: 220px" v-model="queryParams.recruiterDeptId" placeholder="请选择" clearable
                        @change="deptChange">
                        <el-option v-for="dict in deptList" :key="dict.deptId" :label="dict.deptName"
                            :value="dict.deptId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="招商员" prop="recruiterId" v-if="queryParams.putStockType == 'E1'">
                    <el-select style="width: 220px" v-model="queryParams.recruiterId" placeholder="请选择招商员" clearable>
                        <el-option v-for="dict in recruiterList" :key="dict.userId" :label="dict.nickName"
                            :value="dict.userId" />
                    </el-select>
                </el-form-item>
                <!-- 还品入库 -->
                <el-form-item label="来源部门" prop="recruiterDept" v-if="queryParams.putStockType == 'E2'">
                    <el-select style="width: 220px" v-model="queryParams.recruiterDept" placeholder="请选择" clearable>
                        <el-option v-for="dict in returnList" :key="dict.deptId" :label="dict.deptName"
                            :value="dict.deptId" />
                    </el-select>
                </el-form-item>
                <!-- 补样入库 -->
                <el-form-item label="供应商" prop="recruiterDept" v-if="queryParams.putStockType == 'E3'">
                    <el-select v-model="queryParams.recruiterDept" placeholder="请选择供应商" clearable filterable
                        v-selectLoad="selectLoad" :teleported="false" :fit-input-width="true" class="supplierSelect"
                        style="width: 220px" remote :remote-method="searchQuery" :loading="supplierQueryLoading"
                        @clear="handleClear">
                        <el-option v-for="dict in supplierNameOptions" :key="dict.value" :label="dict.label"
                            :value="dict.value">
                        </el-option>
                        <template v-if="supplierLoading">
                            <div class="supplierSelect_icon">
                                <el-icon class="el-select-loading__icon">
                                    <Loading />
                                </el-icon>
                                <span class="el-select-loading__tips">{{ "正在加载" }}</span>
                            </div>
                        </template>
                        <template #loading>
                            <svg class="circular" viewBox="0 0 50 50">
                                <circle class="path" cx="25" cy="25" r="20" fill="none" />
                            </svg>
                        </template>
                    </el-select>
                </el-form-item>

                <el-form-item label="产品部门" prop="stockDeptId">
                    <el-select v-model="queryParams.stockDeptId" placeholder="请选择产品部门" clearable
                        @change="warehouseChange" filterable style="width: 220px">
                        <el-option v-for="dict in warehousedepList" :key="dict.deptId" :label="dict.deptName"
                            :value="dict.deptId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="入库员" prop="stockUserId">
                    <el-select v-model="queryParams.stockUserId" placeholder="请选择入库员" clearable filterable
                        style="width: 220px">
                        <el-option v-for="dict in stockUserList" :key="dict.userId" :label="dict.nickName"
                            :value="dict.userId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="入库时间" prop="putTimeArray">
                    <el-date-picker value-format="YYYY-MM-DD" v-model="queryParams.putTimeArray" type="daterange"
                        range-separator="~" start-placeholder="开始时间" end-placeholder="结束时间" clearable
                        style="width: 220px" />
                </el-form-item>
                <el-form-item label="商品名称" prop="styleName">
                    <el-input v-model="queryParams.styleName" placeholder="请输入" clearable style="width: 220px"
                        @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="类目" prop="categoryIdList">
                    <el-cascader v-model="queryParams.categoryIdList" :options="options" style="width: 220px" clearable
                        collapse-tags filterable @change="handleChange" placeholder="请选择" :props="props" />
                </el-form-item>
                <el-form-item label="库存编码" prop="stockCode">
                    <el-input v-model="queryParams.stockCode" placeholder="请输入" clearable style="width: 220px"
                        @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="入库单号" prop="orderId">
                    <el-input v-model="queryParams.orderId" placeholder="请输入" clearable style="width: 220px"
                        @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="选品部门" prop="coreId">
                    <el-select style="width: 220px" v-model="queryParams.coreId" placeholder="请选择" clearable filterable>
                        <el-option v-for="dict in anchorList" :key="dict.deptId" :label="dict.deptName"
                                    :value="dict.deptId"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div class="form_button">
                <el-button type="primary" @click="handleQuery" :loading="queryLoading">查询</el-button>
                <el-button @click="resetQuery" :loading="queryLoading">重置</el-button>
            </div>
        </searchrevealing>
        <el-card shadow="never">
            <template #header>
                <el-col :span="1.5">
                    <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
                </el-col>
                <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :name="'产品部入库记录入库详单'"
                    @updateColumn="getColmun"></right-toolbar>
            </template>
            <el-table v-loading="loading" :data="selectionRecordList" border @header-dragend="dragEnd">
                <el-table-column label="序号" type="index" width="55" align="center" :fixed="true" />
                <el-table-column v-for="(item, index) in storageRecordColumns" :key="index" :label="item.label"
                    align="center" :prop="item.prop" show-overflow-tooltip :fixed="item.fixed" :width="item.width">
                    <template #default="scope">
                        <image-preview v-if="item.prop == 'productImage'" :src="scope.row.productImage" :width="50"
                            :height="50" />
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="paginationChange" :leftText="statisticsText" />
        </el-card>
    </div>
</template>



<script setup name="StorageRecord" lang="ts">
import { WarehousingQueryParmas, WarehousingVO } from '@/api/group/productOutbound/types'
import { getStorageDetailed, getStickDept, getUserLists, getCategoryLists } from '@/api/group/productOutbound/index'
import { loginDeptList, getOutDeptListAll, getUserById } from '@/api/group/qualityControl'
import { loginSupplierList } from '@/api/group/supplier/index'
import { queryOperationDeptList } from '@/api/group/productSelectionPricing'
const { proxy } = getCurrentInstance() as any;
const storageRecordColumns = ref()
const selectionRecordList = ref<WarehousingVO[]>([]);
const loading = ref(true);
const total = ref(0);
const statisticsText = ref('')
const showSearch = ref(true);
const queryFormRef = ref<ElFormInstance>();
const columnData = ref()

const deptList = ref<{ deptId: string; deptName: string; }[]>([])
const recruiterList = ref<{ userId: string; nickName: string; }[]>([])
const returnList = ref<{ deptId: string; deptName: string; }[]>([])
const anchorList = ref<{ deptName: string; deptId: string }[]>([]);

const queryLoading = ref(false)

const ReasonstorageList = reactive([
    { label: '补样入库', value: 'E3' },
    { label: '还品入库', value: 'E2' },
    { label: '招商入库', value: 'E1' },
    { label: '盘盈入库', value: 'E4' },
    { label: '借调入库', value: 'E5' },
])
// 入库部门
const warehousedepList = ref<{ deptName: string; deptId: string }[]>([])
// 入库员
const stockUserList = ref<{ nickName: string; userId: string }[]>([])

const queryParams = ref<WarehousingQueryParmas>({
    pageNum: 1,
    pageSize: 10,
    putStockType: undefined,
    stockDeptId: undefined,
    stockUserId: undefined,
    orderId: undefined,
    recruiterDeptId: undefined,
    recruiterId: undefined,
    styleName: undefined,
    stockCode: undefined,
    recruiterDept: undefined,
    recruiter: undefined,
    putTimeArray: [],
    groundStartTime: '',
    groundEndTime: '',
    categoryIdList: [],
    coreId: '',
})
const options = ref()
const props = {
    multiple: true
}
const supplierNameOptions = ref<any[]>([])
const supplierNameDate = ref({
    pageNum: 1,
    pageSize: 10,
    supplierName: ''
})
const supplierQueryLoading = ref(false)
const supplierLoading = ref(true)
const supplierNametotal = ref()
/** 供应商select懒加载 */
const selectLoad = async () => {
    if (supplierNameOptions.value.length < supplierNametotal.value) {
        supplierNameDate.value.pageNum++;
        getHmSupplierList()
    }
}
// 获取供应商列表
const getHmSupplierList = async () => {
    supplierLoading.value = true
    const res = await loginSupplierList(supplierNameDate.value)
    const reshandle = res.rows.map((item: any) => (
        {
            label: item.supplierName,
            value: item.id
        }
    ))
    supplierNameOptions.value.push(...reshandle)
    supplierNametotal.value = res.total
    supplierLoading.value = false
}
/** 远程搜索 */
const searchQuery = async (query: string) => {
    supplierQueryLoading.value = true
    supplierNameOptions.value = []
    supplierNameDate.value.pageNum = 1;
    supplierNameDate.value.pageSize = 10
    supplierNameDate.value.supplierName = query
    await getHmSupplierList()
    supplierQueryLoading.value = false
}
/** 清空供应商 */
const handleClear = () => {
    supplierNameDate.value.supplierName = ''
    supplierNameOptions.value = []
    supplierNameDate.value.pageNum = 1;
    supplierNameDate.value.pageSize = 10
    getHmSupplierList()
}
/** 
 * 入库类型切换
*/
const onChange = () => {
    queryParams.value.recruiterDept = undefined
    queryParams.value.recruiterDeptId = undefined
    queryParams.value.recruiterId = undefined
}
/**
 * 获取来源部门信息
 */
const getDeptLists = async () => {
    const res = await loginDeptList()
    deptList.value = res.data
}
/**
 * 获取还品入库主播列表
 */
const getreturnList = async () => {
    const res = await getOutDeptListAll()
    returnList.value = res.data
}
/**
 *  根据招商部获取招商员
 */
const deptChange = async (event: string) => {
    if (event) {
        const res = await getUserById(event)
        recruiterList.value = res.data
        queryParams.value.recruiter = undefined
    } else {
        recruiterList.value = []
        queryParams.value.recruiter = undefined
    }
}
/** 获取类目 */
const getCategoryList = async () => {
    try {
        const res = await getCategoryLists();
        const processedData = renameField(res.data);
        options.value = processedData;
    } catch (error) {
        console.error('Failed to get category list:', error);
        options.value = [];
    }
}
const renameField = (arr: any[]) => {
    return arr.filter(item => item.categoryStatus === 0).map(element => {
        if (element.children) {
            element.children = renameField(element.children);
        }
        return {
            label: element.categoryName,
            value: element.categoryId,
            ...element,
        };
    });
}
// 筛选类目change事件
const handleChange = (val: [string, string, string, string]) => {

}
// 获取选品部门
const getAnchor = async () => {
    const res = await queryOperationDeptList()
    anchorList.value = res.data
}
/** 根据入库部门查询入库员 */
const warehouseChange = async (event: string) => {
    if (event) {
        const res = await getUserLists({ deptId: event })
        stockUserList.value = res.data
        queryParams.value.stockUserId = undefined
    } else {
        stockUserList.value = []
        queryParams.value.stockUserId = undefined
    }
}
/** 查询列表 */
const getList = async () => {
    try {
        loading.value = true;
        if (queryParams.value.putTimeArray && queryParams.value.putTimeArray.length) {
            queryParams.value.groundStartTime = queryParams.value.putTimeArray[0]
            queryParams.value.groundEndTime = queryParams.value.putTimeArray[1]
        } else {
            queryParams.value.groundStartTime = ''
            queryParams.value.groundEndTime = ''
        }
        const res = await getStorageDetailed(queryParams.value);
        selectionRecordList.value = res.rows;
        total.value = res.total;
        statisticsText.value = res.msg
        loading.value = false;
        queryLoading.value = false
    } catch (e) {
    } finally {
        loading.value = false;
    }
};
/** 搜索按钮操作 */
const handleQuery = () => {
    queryLoading.value = true
    queryParams.value.pageNum = 1;
    getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    stockUserList.value = []
    handleClear();
    handleQuery();
};
/** 获取入库部门 */
const getWarehousingDept = async () => {
    const res = await getStickDept()
    warehousedepList.value = res.data
}
/** 导出按钮操作 */
const handleExport = () => {
    proxy?.downloadAsync("basic/stock/getStockInDetailedExport", {
        ...queryParams.value,
    }, `入库详单_${new Date().getTime()}.xlsx`)
}
/** 获取colmun */
const getColmun = async () => {
    const columnDatas = await proxy?.useColumn('产品部入库记录入库详单')
    storageRecordColumns.value = columnDatas.columnCustom
    columnData.value = columnDatas
    queryParams.value.pageSize = columnDatas.columnPageSize || 10
}
/** 拖拽事件 */
const dragEnd = async (newWidth: number, oldWidth: number, column: any, event: MouseEvent) => {
    columnData.value.columnCustom.map((item: any) => {
        if (item.prop == column.property) {
            item.width = newWidth
        }
    })
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
}
/** 页数变化 */
const paginationChange = async () => {
    await getList();
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
    getColmun()
}
onMounted(async () => {
    queryParams.value.pageNum = 1;
    await getColmun();
    await getList();
    getAnchor();
    getreturnList();
    getWarehousingDept();
    getCategoryList();
    getDeptLists();
})

</script>
<style lang="scss" scoped>
.mb96 {
    margin-bottom: 96px;
}

:deep(.el-card__header) {
    display: flex;
    justify-content: flex-end;
}

.form_button {
    display: flex;
    justify-content: flex-end;
}

.circular {
    display: inline;
    height: 30px;
    width: 30px;
    animation: loading-rotate 2s linear infinite;
}

.path {
    animation: loading-dash 1.5s ease-in-out infinite;
    stroke-dasharray: 90, 150;
    stroke-dashoffset: 0;
    stroke-width: 2;
    stroke: var(--el-color-primary);
    stroke-linecap: round;
}

.supplierSelect {
    :deep(.el-popper) {
        left: 0 !important;
        top: 34px !important;
        z-index: 7000 !important;
        width: 100% !important;
    }
}

:deep(.el-tabs__content) {
    overflow: visible !important;
}

.supplierSelect_icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
}

.el-select-loading__tips {
    color: #606266;
    font-size: 14px;
}
</style>